/*
 * 公司视图
 * @Author: ljb
 * @Date: 2018-03-27 17:52:07
 * @Last Modified by: ljb
 * @Last Modified time: 2019-03-14 18:03:13
 */
<style lang="less" rel="stylesheet/less" type="text/less" scoped>
	@deep: ~">>>";
    .v-customer-store-views {
        padding: 20px;
        .preview-image {
            display: block;
            margin-top: 10px;
        }
	}
	@{deep} .ivu-modal-body{
		min-height: 460px;
	}

</style>

<template>

	<div class="v-customer-store-views">

		<Tabs
			type="card"
			@on-click="changeTab">

			<TabPane
				:label="$t('common.create')"
				name="新增">

				<store-create
          :group-categories="group_categories"
					ref="create"
					@post="postData"/>

			</TabPane>

			<TabPane
				:label="$t('common.check')"
				name="查看">

				<!-- <search-form @search="confirmSearch"/> -->

				<store-index
					:loading="table_loading"
					:company="customer_companies.data"
					@edit="companyDetail"
					@delete="deleteCompany"
				/>

				<br>

				<!-- 分页组件 -->
				<Row
					type="flex"
					justify="center">
					<Page
						:total="customer_companies.total"
						:current="customer_companies.current_page"
						:page-size="query_info.per_page"
						placement="top"
						show-sizer
						show-total
						@on-change="pageChange"
						@on-page-size-change="perPageChange"/>
				</Row>

			</TabPane>

		</Tabs>

		<Modal
			v-model="show_modal"
			:title="$t('store.store_info')"
			class-name="vertical-middle-modal">

			<!-- 店铺编辑组件 -->
			<store-edit
				v-if="show_modal"
				:company-detail="company_detail"
				:show-modal="show_modal"
        :group-categories="group_categories"
        @update="updateCompany"/>

			<div slot="footer"/>

		</Modal>

	</div>

</template>

<script>

import API_LIST from 'src/API_LIST';
import { $t } from 'src/i18n/index';

import { mapMutations } from 'vuex';

import qs from 'qs';

import storeCreate from './create';
import storeIndex from './index';
import storeEdit from './edit';

// import searchForm from './search-form';

export default {

	name: 'CompanyViews',

	components: {
		storeCreate,

		storeIndex,

		storeEdit,

		// searchForm,
	},
	data() {
		return {

			query_info: {
				page: 1,

				per_page: 20,

				keyword: '',
			},

			search_info: {
				page: 1,

				per_page: 20,
			}, // 分页信息

			table_loading: false, // 表格更新时的loading

			show_modal: false, // 弹框的控制

			company_detail: {}, // 公司详情

			customer_companies: {}, // 公司信息

      group_categories: [], // 产品种类成组
		};
	},

  mounted() {
    this.fetchProductCreateInfo();
  },

	methods: {

		...mapMutations('spinShow', [
			'showSpin',
			'closeSpin',
		]),

		/**
         * 切换tab
         * @param  {string} tab_name {tab的name}
         * @return {undefined}
         */
		changeTab(tab_name) {
			if (tab_name === '查看') {
				this.fetchCompanyList(this.query_info);
				this.$refs.create.handleReset('formValidate');
			} else {
				this.customer_companies.data = [];
			}
		},

		/**
         * 页码改变
         * @param  {string} pageNumber {当前页码}
         * @return {undefined}
         */
		pageChange(pageNumber) {
			this.search_info.page = pageNumber;

			this.search_info.per_page = this.query_info.per_page;

			this.fetchCompanyList(this.search_info);
		},

		/**
         * 每页显示数改变
         * @param  {string} per_page {当前每页显示数}
         * @return {undefined}
         */
		perPageChange(per_page) {
			this.search_info.per_page = per_page;

			this.query_info.per_page = per_page;

			this.fetchCompanyList(this.query_info);
		},

		/**
         * 确认搜索
         * @param  {Object} param {搜索的参数对象}
         * @return {undefined}
         */
		confirmSearch(param) {
			this.query_info.keyword = param.keyword;

			this.search_info = JSON.parse(JSON.stringify(this.query_info));

			this.fetchCompanyList(this.query_info);
		},

		/**
         * 新增公司的post数据
		 * @param {Object} param {create传参的对象}
         * @return {undefined}
         */
		postData(param) {
			this.showSpin(this.$t('common.please_wait'));

			this.$http.post(API_LIST.CUST_COMPANY, param)

				.then(({ data }) => {
					if (Number(data.code) !== 0) throw new Error(data.error);

					this.$Message.success(this.$t('common.create_success'));

					this.$refs.create.handleReset('formValidate');
				})

				.catch((err) => {
					this.$Message.error(err.message);
				})
				.then(this.closeSpin);
		},

		/**
         * 获取公司详情
         * @param  {Object} detail {当前查看的职员信息}
         * @return {undefined}
         */
		companyDetail(detail) {
			this.company_detail = detail;

			this.show_modal = true;
		},

		/**
         * 更新公司信息
         * @param  {string} id    {需要更新的店铺的id}
         * @param  {Object} param {需要的参数对象}
         * @return {undefined}
         */
		updateCompany(id, param) {
			this.showSpin(this.$t('common.please_wait'));

			this.$http.post(`${API_LIST.CUST_COMPANY}/${id}`, param)

				.then(({ data }) => {
					if (Number(data.code) !== 0) throw new Error(data.error);
          console.log(this.data);
					
					this.$Message.success(this.$t('common.update_success'));

					this.show_modal = false;

					this.fetchCompanyList(this.search_info);
				})

				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})
				.then(this.closeSpin);
		},

		/**
         * 获取公司列表
         * @param  {Object} param {搜索列表的参数}
         * @return {undefined}
         */
		fetchCompanyList(param) {
			this.table_loading = true;

			const query_str = qs.stringify(param);

			this.$http.get(`${API_LIST.CUST_COMPANY}?${query_str}`)

				.then(({ data }) => {
					if (Number(data.code) !== 0) throw new Error(data.error);

					this.customer_companies = data.customer_companies;
				})

				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})

				.then(() => { this.table_loading = false; });
		},

		/**
         * 删除公司信息
         * @param  {Object} row {店铺对象}
         * @return {undefined}
         */
		deleteCompany(id) {
			this.$Modal.confirm({

				title: this.$t('product.tip'), // '温馨提示',
				content: this.$t('product.is_delete'), // '删除之后将无法恢复，确定吗？',
				onOk: () => {
					const param = {

						_method: 'DELETE',

					};
					this.table_loading = true;

					this.$http.post(`${API_LIST.CUST_COMPANY}/${id}`, param)

						.then(({ data }) => {
							if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

							this.fetchCompanyList(this.search_info);

							this.$Message.success(this.$t('common.delete_success'));
						})

						.catch((err) => {
							this.$Message.error(err.message || err.statusText);
						})

						.then(() => { this.table_loading = false; });
				},
				onCancel: () => {},

			});	
		},


    /**
     * 获取创建产品时所需信息
     * @return {undefined}
     */
    fetchProductCreateInfo() {
      this.showSpin($t('common.please_wait'));

      return this.$http.get(`${API_LIST.CUST_PRODUCT}/create`)

        .then(({ data }) => {
          if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

          this.group_categories = data.group_categories;
        })

        .catch((err) => {
          this.$Message.error(err.message || err.statusText);
        })

        .then(this.closeSpin);
    },
	},
};
</script>
